const Router = require('express')
const swaggerJsdoc = require('swagger-jsdoc');
const router = new Router()
const feeding = require('./controllers/feeding')
const auth = require('./controllers/auth')
const population = require('./controllers/populations')
const populationGrowth = require('./controllers/population_growth')
const sensor = require('./controllers/sensors')
const food = require('./controllers/food')
const equipment = require('./controllers/equipment')
const types = require('./controllers/types')
const indication = require('./controllers/indication')
const jwt = require('jsonwebtoken');


function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    console.log(authHeader)
    const token = authHeader && authHeader.split(' ')[1];
    if (token == null) return res.sendStatus(401);

    jwt.verify(token, 'secret_key', (err, user) => {
        if (err) return res.sendStatus(403);
        console.log(user)
        req.user = user;
        next();
    });
}

const { Pool } = require('pg');
const pool = new Pool({
    user: 'postgres',
    host: 'project_data_base',
    //host: '127.0.0.1',
    database: 'postgres',
    password: '1234',
    port: 5432,
});

async function checkUserRole(req, res, next) {
    const userId = req.user.email;
    const requiredRole = 'Admin';


    try {
       
        const client = await pool.connect();
        const result = await client.query('SELECT r.role_name FROM users as u join role as r on u.role_id=r.id WHERE u.email=$1', [userId]);
        
        const userRole = result.rows[0];
        console.log(req.user)
        if (userRole.role_name !== requiredRole) {
            return res.status(403).json({ message: 'Insufficient permissions' });
        }
        
        client.release();
        
        next();
    } catch (err) {
        console.error('Error executing query', err.stack);
        res.status(500).send('Internal Server Error');
    }
}



//Auth endpoints
router.post('/register', auth.registration)
router.post('/login', auth.login)
router.post('/refresh-token', auth.refreshToken)
router.get('/users', authenticateToken, checkUserRole, auth.users)

// Feeding endpoints
router.get('/feeding', authenticateToken, feeding.feedingGet)
router.post('/feeding', authenticateToken, feeding.feedingPost)
// router.delete('/feeding', authenticateToken, feeding.feedingDelete)
// router.put('/feeding', authenticateToken, feeding.feedingPut) 

// Population endpoints
router.get('/population', authenticateToken, population.populationGet)
router.post('/population', authenticateToken, population.populationPost)
router.get('/code', authenticateToken, population.populationCode)
router.post('/pool', authenticateToken, population.populationPoolPost)
// router.delete('/population', authenticateToken, population.populationDelete) 
// router.put('/population', authenticateToken, population.populationPut) 

// Population_growth endpoints
router.get('/population_growth', authenticateToken, populationGrowth.populationGrowthGet)
router.post('/population_growth', authenticateToken, populationGrowth.populationGrowthPost)
// router.delete('/population_growth', authenticateToken, populationGrowth.populationGrowthDelete) 
// router.put('/population_growth', authenticateToken, populationGrowth.populationGrowthPut) 

// Food endpoints
router.get('/food', authenticateToken, food.foodGet)
router.post('/food', authenticateToken, food.foodPost)
// router.delete('/food', authenticateToken, food.foodDelete) 
// router.put('/food', authenticateToken, food.foodPut) 

// Sensors endpoints
router.get('/sensors', authenticateToken, sensor.sensorGet)
router.post('/sensors', authenticateToken, sensor.sensorPost)
// router.delete('/sensors', authenticateToken, sensor.sensorDelete) 
// router.put('/sensors', authenticateToken, sensor.sensorPut) 

// Equipment endpoints
router.get('/equipment', authenticateToken, equipment.equipmentGet)
router.post('/equipment', equipment.equipmentPost)
// router.delete('/equipment', authenticateToken, checkUserRole, equipment.equipmentDelete) 
// router.put('/equipment', authenticateToken, checkUserRole, equipment.equipmentPut) 

// Types endpoints
router.get('/types', authenticateToken, types.typesGet)
router.post('/types', authenticateToken, checkUserRole, types.typesPost)
router.delete('/types', authenticateToken, checkUserRole, types.typesDelete) 
// router.put('/types', authenticateToken, checkUserRole, types.typesPut) 

router.get('/subtypes', authenticateToken,  types.subTypesGet)
router.post('/subtypes', authenticateToken, checkUserRole, types.subTypesPost)
router.delete('/subtypes', authenticateToken, checkUserRole, types.subTypesDelete)
// router.put('/subtypes', authenticateToken, checkUserRole, types.subTypesPut) 

router.get('/indication', authenticateToken, indication.indicationGet)
router.post('/indication', authenticateToken, indication.indicationPost)
// router.delete('/indication', authenticateToken, checkUserRole, indication.indicationDelete) 
// router.put('/indication', authenticateToken, checkUserRole, indication.indicationPut) 

module.exports = router
